﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.ServiceBus.Extensions.Authentication
{
    /// <summary>
    /// JWT鉴权
    /// </summary>
    public static class JwtAuthentication
    {
        /// <summary>
        /// 启用JWT鉴权
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddJwtAuthSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            var authenticationProviderKey = "MyWeb.ScheduledTasks";
            #region Jwt验证
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(authenticationProviderKey, options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        //JWT有一些默认的属性，就是给鉴权时就可以筛选了
                        ValidateIssuer = true,//是否验证Issuer
                        ValidateAudience = true,//是否验证Audience
                        ValidateLifetime = true,//是否验证失效时间---默认还添加了300s后才过期
                        ClockSkew = TimeSpan.FromSeconds(0),//token过期后立马过期
                        ValidateIssuerSigningKey = true,//是否验证SecurityKey

                        ValidAudience = "http://172.18.18.250:5291",//Audience,需要跟前面签发jwt的设置一致
                        ValidIssuer = "http://localhost:7200",//Issuer，这两项和前面签发jwt的设置一致
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI2a2EJ7m872v0afyoSDJT2o1+SitIeJSWtLJU8/Wz2m7gStexajkeD")),//拿到SecurityKey
                    };
                });
            #endregion
        }
    }
}
